package com.ruoyi.system.service.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import com.ruoyi.common.annotation.DataScope;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.entity.BusinessInfo;
import com.ruoyi.system.entity.BusinessShareholder;
import com.ruoyi.system.entity.SocialInfo;
import com.ruoyi.system.service.IEBusinessInfoService;
import com.ruoyi.system.service.IEBusinessShareholderService;
import com.ruoyi.system.service.IEBusinessSocialService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.system.mapper.EPerfectLogMapper;
import com.ruoyi.system.domain.EPerfectLog;
import com.ruoyi.system.service.IEPerfectLogService;

/**
 * 企业信息完善记录Service业务层处理
 *
 * @author ruoyi
 * @date 2022-03-23
 */
@Service
public class EPerfectLogServiceImpl implements IEPerfectLogService
{
    @Autowired
    private EPerfectLogMapper ePerfectLogMapper;

    @Autowired
    IEBusinessInfoService eBusinessInfoService;
    @Autowired
    IEBusinessShareholderService eBusinessShareholderService;
    @Autowired
    IEBusinessSocialService eBusinessSocialService;
    /**
     * 查询企业信息完善记录
     *
     * @param id 企业信息完善记录主键
     * @return 企业信息完善记录
     */
    @Override
    public EPerfectLog selectEPerfectLogById(Long id)
    {
        return ePerfectLogMapper.selectEPerfectLogById(id);
    }

    /**
     * 查询企业信息完善记录列表
     *
     * @param ePerfectLog 企业信息完善记录
     * @return 企业信息完善记录
     */
    @Override
    @DataScope()
    public List<EPerfectLog> selectEPerfectLogList(EPerfectLog ePerfectLog)
    {
        return ePerfectLogMapper.selectEPerfectLogList(ePerfectLog);
    }

    /**
     * 新增企业信息完善记录
     *
     * @param ePerfectLog 企业信息完善记录
     * @return 结果
     */
    @Override
    public int insertEPerfectLog(EPerfectLog ePerfectLog)
    {
        ePerfectLog.setCreateTime(DateUtils.getNowDate());
        return ePerfectLogMapper.insertEPerfectLog(ePerfectLog);
    }

    /**
     * 修改企业信息完善记录
     *
     * @param ePerfectLog 企业信息完善记录
     * @return 结果
     */
    @Override
    public int updateEPerfectLog(EPerfectLog ePerfectLog)
    {
        return ePerfectLogMapper.updateEPerfectLog(ePerfectLog);
    }

    /**
     * 批量删除企业信息完善记录
     *
     * @param ids 需要删除的企业信息完善记录主键
     * @return 结果
     */
    @Override
    public int deleteEPerfectLogByIds(Long[] ids)
    {
        return ePerfectLogMapper.deleteEPerfectLogByIds(ids);
    }

    /**
     * 删除企业信息完善记录信息
     *
     * @param id 企业信息完善记录主键
     * @return 结果
     */
    @Override
    public int deleteEPerfectLogById(Long id)
    {
        return ePerfectLogMapper.deleteEPerfectLogById(id);
    }

    @Override
    public EPerfectLog perfectInfo(Long id, LoginUser loginUser) {
        EPerfectLog ePerfectLog=selectEPerfectLogById(id);
        if(null==ePerfectLog||"OK".equals(ePerfectLog.getPerfectState())){
            return ePerfectLog;
        }
        if("DRAWER".equals(ePerfectLog.getPerfectState())){
            /**工商照面信息处理用于处理出票人*/
            setBusinessInfoByNameToOk(ePerfectLog, loginUser);
            return ePerfectLog;
        }
        if("ACCEPTOR".equals(ePerfectLog.getPerfectState())){
            /**工商照面信息处理用于处理承兑人*/
            setBusinessInfoByNameToDrawer(ePerfectLog,loginUser);
            /**工商照面信息处理用于处理出票人*/
            setBusinessInfoByNameToDrawer(ePerfectLog,loginUser);
            return ePerfectLog;
        }
        if("SOCIALINFO".equals(ePerfectLog.getPerfectState())){
            /**社保信息处理*/
            setSocialInfo(ePerfectLog,loginUser);
            /**工商照面信息处理用于处理承兑人*/
            setBusinessInfoByNameToDrawer(ePerfectLog,loginUser);
            /**工商照面信息处理用于处理出票人*/
            setBusinessInfoByNameToOk(ePerfectLog,loginUser);
            return ePerfectLog;
        }
        if("SHAREHOLDER".equals(ePerfectLog.getPerfectState())){
            /**股东信息处理*/
            setBusinessShareholder(ePerfectLog,loginUser);
            /**社保信息处理*/
            setSocialInfo(ePerfectLog,loginUser);
            /**工商照面信息处理用于处理承兑人*/
            setBusinessInfoByNameToDrawer(ePerfectLog,loginUser);
            /**工商照面信息处理用于处理出票人*/
            setBusinessInfoByNameToOk(ePerfectLog,loginUser);
            return ePerfectLog;
        }
        if("BUSINESSINFO".equals(ePerfectLog.getPerfectState())){
            /**工商照面信息处理用于处理贴现人*/
            setDiscountApplicantDept(ePerfectLog,loginUser);
            /**股东信息处理*/
            setBusinessShareholder(ePerfectLog,loginUser);
            /**社保信息处理*/
            setSocialInfo(ePerfectLog,loginUser);
            /**工商照面信息处理用于处理承兑人*/
            setBusinessInfoByNameToDrawer(ePerfectLog,loginUser);
            /**工商照面信息处理用于处理出票人*/
            setBusinessInfoByNameToOk(ePerfectLog,loginUser);
            return ePerfectLog;
        }
        return ePerfectLog;
    }

    @Override
    public void importEPerfectLog(Long taskId, List<EPerfectLog> ePerfectLogs,String operName,LoginUser loginUser) {
        for(EPerfectLog ePerfectLog:ePerfectLogs){
            if(StringUtils.isNotEmpty(ePerfectLog.getTicketCode())){
                ePerfectLog.setTaskId(taskId);
                ePerfectLog.setCreateBy(operName);
                ePerfectLog.setUserId(loginUser.getUserId());
                ePerfectLog.setDeptId(loginUser.getDeptId());
                ePerfectLog.setPerfectState("BUSINESSINFO");
                insertEPerfectLog(ePerfectLog);
            }
        }
        allEPerfectLog(taskId,loginUser);
    }

    @Override
    public void allEPerfectLog(Long taskId,LoginUser loginUser){
        EPerfectLog ePerfectLog=new EPerfectLog();
        ePerfectLog.setTaskId(taskId);
        List<EPerfectLog> ePerfectLogList=selectEPerfectLogList(ePerfectLog);
        for(EPerfectLog perfectLog:ePerfectLogList){
            /**工商照面信息处理用于处理贴现人*/
            setDiscountApplicantDept(perfectLog,loginUser);
            /**股东信息处理*/
            setBusinessShareholder(perfectLog,loginUser);
            /**社保信息处理*/
            setSocialInfo(perfectLog,loginUser);
            /**工商照面信息处理用于处理承兑人*/
            setBusinessInfoByNameToDrawer(perfectLog,loginUser);
            /**工商照面信息处理用于处理出票人*/
            setBusinessInfoByNameToOk(perfectLog,loginUser);
        }
    }

    @Override
    public void oneEPerfectLog(Long taskId,LoginUser loginUser){
        EPerfectLog ePerfectLog=new EPerfectLog();
        ePerfectLog.setTaskId(taskId);
        List<EPerfectLog> ePerfectLogList=selectEPerfectLogList(ePerfectLog);
        for(EPerfectLog perfectLog:ePerfectLogList){
            perfectInfo(perfectLog.getId(),loginUser);
        }
    }

    @Override
    public Boolean isUnfinished(Long taskId) {
       Long num = ePerfectLogMapper.isUnfinishedByTaskId(taskId);
       if(num>0){
           return true;
       }
        return false;
    }

    private void setBusinessInfoByNameToOk(EPerfectLog ePerfectLog,LoginUser loginUser) {
        BusinessInfo drawer=eBusinessInfoService.getBusinessInfoByName(ePerfectLog.getDrawerName(),loginUser);
        if(null!=drawer.getData()){
            //出票人证件代码（使用其中的组织机构代码  实际为：MA1MUUMY-2  填充为：MA1MUUMY2）
            //由于模板不正确，根据要求更改为社会同一信用代码
            ePerfectLog.setDrawerCardCode(drawer.getData().getCreditNo());
            ePerfectLog.setPerfectState("OK");
            //查询任务并完善任务状态
            ePerfectLogMapper.updateTask(ePerfectLog.getTaskId());
            updateEPerfectLog(ePerfectLog);
        }
    }

    private void setBusinessInfoByNameToDrawer(EPerfectLog ePerfectLog,LoginUser loginUser) {
        BusinessInfo acceptor=eBusinessInfoService.getBusinessInfoByName(ePerfectLog.getAcceptorName(),loginUser);
        //{"data":{"econKind":"其他股份有限公司(非上市)","registCapi":"2000000 万人民币","id":"b6e67254-4688-406b-9886-a0426117bd20","currency_unit":"CNY","belongOrg":"辽宁省市场监督管理局","status":"存续","termStart":"2021-06-07","format_name":"辽沈银行股份有限公司","historyNames":[],"revoke_date":"-","address":"辽宁省沈阳市沈河区北站一路43号","regNo":"210000004975832","tags":[],"domain":"J6600","creditNo":"91210000MA1153JT3P","categoryNew":"0115601","orgNo":"MA1153JT3","name":"辽沈银行股份有限公司","startDate":"2021-06-07","scope":"许可项目：银行业务（依法须经批准的项目，经相关部门批准后方可开展经营活动，具体经营项目以审批结果为准）","operName":"王默涵","districtCode":"210103","new_status":"存续","endDate":"-","title":"法定代表人","checkDate":"2021-06-07","actualCapi":"-","termEnd":"-","econKindCode":"1229","revoke_reason":"-","type_new":"01"},"sign":"b093ecec2ae6477b99570255afac040b","status":"200","message":"操作成功"}
        //承兑人证件代码（使用其中的组织机构代码  实际为：MA1153JT-3  填充为：MA1153JT3）
        //由于模板不正确，根据要求更改为社会同一信用代码
        if(null!=acceptor.getData()){
            ePerfectLog.setAcceptorCardCode(acceptor.getData().getCreditNo());
            ePerfectLog.setPerfectState("DRAWER");
            updateEPerfectLog(ePerfectLog);
        }
    }

    private void setSocialInfo(EPerfectLog ePerfectLog,LoginUser loginUser) {
        //贴现申请人企业规模(根据其中的人员数量进行判断参考依据国标文件)
        SocialInfo socialInfo=eBusinessSocialService.getSocialInfo(ePerfectLog.getDiscountApplicantCardCode(),loginUser);
        if(null!=socialInfo.getData()&&null!=socialInfo.getData().getItems()&&socialInfo.getData().getItems().size()>0){
            String num=socialInfo.getData().getItems().get(0).getSocialSecurity().getUnenploymentNum();
            if(num.equals("-")){
                ePerfectLog.setDiscountApplicantEnterpriseScale("CS03");
            }else{
                Long date=Long.parseLong(num.replace("人",""));
                if(date>=300){
                    //大 CS01
                    ePerfectLog.setDiscountApplicantEnterpriseScale("CS01");
                }else if(date>=100){
                    //中 CS02
                    ePerfectLog.setDiscountApplicantEnterpriseScale("CS02");
                }else{
                    //小 CS03
                    ePerfectLog.setDiscountApplicantEnterpriseScale("CS03");
                }
            }
        }else{
            ePerfectLog.setDiscountApplicantEnterpriseScale("CS03");
        }
        ePerfectLog.setPerfectState("ACCEPTOR");
        updateEPerfectLog(ePerfectLog);
    }

    private void setBusinessShareholder(EPerfectLog ePerfectLog,LoginUser loginUser) {
        //贴现申请人经济成分(根据其中的第一股东进行判断)
        BusinessShareholder businessShareholder=eBusinessShareholderService.getBusinessShareholder(ePerfectLog.getDiscountApplicantCardCode(),loginUser);
        if(null!=businessShareholder.getData()&&null!=businessShareholder.getData().getItems()&&businessShareholder.getData().getItems().size()>0 ){
            String stockType=businessShareholder.getData().getItems().get(0).getStockType();
            if(isA0101(stockType)){
                ePerfectLog.setDiscountApplicantEconomicSector("A0101");//国有相对控股
            }else if(isA0201(stockType)){
                ePerfectLog.setDiscountApplicantEconomicSector("A0201");//集体相对控股
            }else if(isB0201(stockType)){
                ePerfectLog.setDiscountApplicantEconomicSector("B0201");//港澳台相对控股
            }else if(isB0301(stockType)){
                ePerfectLog.setDiscountApplicantEconomicSector("B0301");//外商相对控股
            }else{
                ePerfectLog.setDiscountApplicantEconomicSector("B0101");//私人相对控股
            }
        }else{
            ePerfectLog.setDiscountApplicantEconomicSector("B0101");//私人相对控股
        }
        ePerfectLog.setPerfectState("SOCIALINFO");
        updateEPerfectLog(ePerfectLog);
    }

    private boolean isA0101(String stockType){
        String A0101="管理机构@" +
                "国家行政部门@" +
                "国家机关@" +
                "国家授权投资部门@" +
                "国家授权投资的机构或部门@" +
                "国家授权投资机构@" +
                "国泰证券有限公司湖北公司@" +
                "国务院、省级人民政府、经授权的机构或部门@" +
                "国营@" +
                "国营松江胶合板厂@" +
                "国有@" +
                "国有独资@" +
                "国有股@" +
                "国有经济@" +
                "国有经济内资企业法人@" +
                "国有控股@" +
                "国有企业@" +
                "国有企业法人@" +
                "行政部门@" +
                "行政村@" +
                "行政单位@" +
                "行政单位法人@" +
                "行政法人@" +
                "行政机关@" +
                "行政机关法人@" +
                "行政事业@" +
                "行政事业单位@" +
                "行政事业法人@" +
                "机关@" +
                "机关（非法人）@" +
                "机关、事业单位法人@" +
                "机关、事业法人@" +
                "机关单位@" +
                "机关法＜@" +
                "机关法人@" +
                "机关法人登记证@" +
                "机关非法人@" +
                "机关事业单位法人@" +
                "机关事业法人@" +
                "机机关法人@" +
                "基层组织@" +
                "居委会@" +
                "军事机关@" +
                "农民专业合作社@" +
                "企业法人（国有控股）@" +
                "全民@" +
                "全民所胡制@" +
                "全民所有制@" +
                "全民所有制分支机构（非法人）@" +
                "全民所有制企业@" +
                "全民所有制企业法人@" +
                "全名所有制@" +
                "群众团体@" +
                "群众自治组织@" +
                "人民政府@" +
                "商务单位@" +
                "社会@" +
                "社会公共股@" +
                "社会公众股@" +
                "社会团体@" +
                "社会团体法人@" +
                "社居委@" +
                "社团@" +
                "社团法人@" +
                "社团组织@" +
                "事业编制@" +
                "事业单位@" +
                "事业单位（非法人）@" +
                "事业单位法人@" +
                "事业单位法人证@" +
                "事业单位法人证书@" +
                "事业单位机关法人@" +
                "事业法人单位@" +
                "事业法人法人@" +
                "事业法人证@" +
                "事业关法人@" +
                "事业机关@" +
                "事业机关法人@" +
                "事业业法人@" +
                "有限公司(国有独资)@" +
                "有限公司(国有独资－国家授权投资主体)@" +
                "有限责任公（国有独资）@" +
                "有限责任公司（国有独资)@" +
                "有限责任公司（国有独资）@" +
                "有限责任公司(国有独资)@" +
                "有限责任公司(国有控股)@" +
                "有限责任公司（国有控股）@" +
                "政府@" +
                "政府/部/门@" +
                "政府部门@" +
                "政府单位@" +
                "政府法人@" +
                "政府行政机构@" +
                "政府机构@" +
                "政府机关@" +
                "政府派出机构";
        if(Arrays.asList(A0101.split("@")).contains(stockType)){
            return true;
        }
        return false;
    }
    private boolean isA0201(String stockType){
        String A0201="集体@" +
                "集体法人@" +
                "集体经济@" +
                "集体企业@" +
                "集体企业法人@" +
                "集体企业所有制@" +
                "集体所有制@" +
                "集体所有制(股份合作制)@" +
                "集体所有制(股份合作制-股份制)@" +
                "集体所有制(合作制)@" +
                "集体所有制企业@" +
                "集体所有制企业法人";
        if(Arrays.asList(A0201.split("@")).contains(stockType)){
            return true;
        }
        return false;
    }
    private boolean isB0201(String stockType){
        String B0201="港、澳、台投资有限合伙企业@" +
                "港澳台投资者@" +
                "股份有限公司(台港澳合资，上市)@" +
                "股份有限公司(台港澳合资，未上市)@" +
                "股份有限公司(台港澳与境内合资，上市)@" +
                "股份有限公司(台港澳与境内合资，未上市)@" +
                "股份有限公司(台港澳与外国投资者合资，上市)@" +
                "股份有限公司(台港澳与外国投资者合资，未上市)@" +
                "香港@" +
                "香港企业@" +
                "有限责任公司(台港澳法人独资)@" +
                "有限责任公司(台港澳非法人经济组织独资)@" +
                "有限责任公司(台港澳合资)@" +
                "有限责任公司(台港澳与境内合资)@" +
                "有限责任公司(台港澳与境内合作)@" +
                "有限责任公司(台港澳与外国投资者合资)@" +
                "有限责任公司(台港澳自然人独资)@" +
                "中国香港";
        if(Arrays.asList(B0201.split("@")).contains(stockType)){
            return true;
        }
        return false;
    }
    private boolean isB0301(String stockType){
        String B0301="非公司外商投资企业（中外合作）@" +
                "股份有限公司(外商合资，上市)@" +
                "股份有限公司(外商合资，未上市)@" +
                "股份有限公司(外资)@" +
                "股份有限公司(中外合资，上市)@" +
                "股份有限公司(中外合资，未上市)@" +
                "合伙企业(外资)@" +
                "境外企业或经济组织@" +
                "境外社会公众股@" +
                "外商投资投资性公司@" +
                "外商投资有限合伙企业@" +
                "外资合伙企业@" +
                "有限责任公司(外国法人独资)@" +
                "有限责任公司(外国非法人经济组织独资)@" +
                "有限责任公司(外国自然人独资)@" +
                "有限责任公司(外商合资)@" +
                "有限责任公司(外资)@" +
                "有限责任公司(中外合资)@" +
                "有限责任公司(中外合作)";
        if(Arrays.asList(B0301.split("@")).contains(stockType)){
            return true;
        }
        return false;
    }
    private void setDiscountApplicantDept(EPerfectLog ePerfectLog,LoginUser loginUser) {
        BusinessInfo discountApplicant=eBusinessInfoService.getBusinessInfoByName(ePerfectLog.getDiscountApplicantName(),loginUser);
        if(null!=discountApplicant.getData()&&StringUtils.isNotEmpty(discountApplicant.getData().getDomain())){
            ePerfectLog.setDiscountApplicantCardCode(discountApplicant.getData().getCreditNo());
            //贴现申请人国民经济部门
            ePerfectLog.setDiscountApplicantDept("C01");//此参数默认
            //贴现申请人行业(使用其中的行业代码)
           String discountApplicantIndustry=discountApplicant.getData().getDomain().substring(0,3);
            if(StringUtils.isNotEmpty(discountApplicantIndustry)&&discountApplicantIndustry.contains("J")){
                ePerfectLog.setDiscountApplicantIndustry("");
            }else{
                ePerfectLog.setDiscountApplicantIndustry(discountApplicantIndustry);
            }
            //贴现申请人地区代码(使用其中的地区代码)
            ePerfectLog.setDiscountApplicantAreaCode(discountApplicant.getData().getDistrictCode().substring(0,2)+"0000");
            ePerfectLog.setPerfectState("");
            ePerfectLog.setPerfectState("SHAREHOLDER");
            updateEPerfectLog(ePerfectLog);
        }
    }
}
